<template>
  <div class="exam">
    <!-- 左侧题目导航列表 -->
    <div class="question-nav left-panel">
      <h3>题目列表</h3>
      <div class="nav-sections">
        <!-- 单选题导航 -->
        <div v-if="randomSingleQuestions.length" class="nav-section">
          <div class="nav-title">单选题</div>
          <div class="nav-items">
            <div v-for="(_, index) in randomSingleQuestions" 
                 :key="'single' + index"
                 :class="['nav-item', { 'answered': answeredQuestions.has('single-' + index) }]"
                 @click="scrollToQuestion('single-' + index)">
              {{ index + 1 }}
            </div>
          </div>
        </div>
        <!-- 多选题导航 -->
        <div v-if="randomMultiQuestions.length" class="nav-section">
          <div class="nav-title">多选题</div>
          <div class="nav-items">
            <div v-for="(_, index) in randomMultiQuestions" 
                 :key="'multi' + index"
                 :class="['nav-item', { 'answered': answeredQuestions.has('multi-' + index) }]"
                 @click="scrollToQuestion('multi-' + index)">
              {{ index + 1 }}
            </div>
          </div>
        </div>
        <!-- 判断题导航 -->
        <div v-if="randomJudgeQuestions.length" class="nav-section">
          <div class="nav-title">判断题</div>
          <div class="nav-items">
            <div v-for="(_, index) in randomJudgeQuestions" 
                 :key="'judge' + index"
                 :class="['nav-item', { 'answered': answeredQuestions.has('judge-' + index) }]"
                 @click="scrollToQuestion('judge-' + index)">
              {{ index + 1 }}
            </div>
          </div>
        </div>
        <!-- 填空题导航 -->
        <div v-if="randomFillQuestions.length" class="nav-section">
          <div class="nav-title">填空题</div>
          <div class="nav-items">
            <div v-for="(_, index) in randomFillQuestions" 
                 :key="'fill' + index"
                 :class="['nav-item', { 'answered': answeredQuestions.has('fill-' + index) }]"
                 @click="scrollToQuestion('fill-' + index)">
              {{ index + 1 }}
            </div>
          </div>
        </div>
        <!-- 简答题导航 -->
        <div v-if="randomEssayQuestions.length" class="nav-section">
          <div class="nav-title">简答题</div>
          <div class="nav-items">
            <div v-for="(_, index) in randomEssayQuestions" 
                 :key="'essay' + index"
                 :class="['nav-item', { 'answered': answeredQuestions.has('essay-' + index) }]"
                 @click="scrollToQuestion('essay-' + index)">
              {{ index + 1 }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要答题区域 -->
    <div class="main-content">
      <div class="exam-content">
        <h1 class="exam-title">试卷：{{ examConfig.examName }}</h1>
        <div v-if="loading">加载中...</div>
        <div v-else-if="examDetail" class="questions-container">
          <!-- 单选题 -->
          <div v-if="randomSingleQuestions.length > 0" class="question-section">
            <h2>一、单选题（共{{ examConfig.singleCount }}题，每题{{ examConfig.scores.single }}分）</h2>
            <div v-for="(question, index) in randomSingleQuestions" 
                 :key="question.record_id" 
                 :id="'single-' + index"
                 class="question-item">
              <div class="question-title">
                {{ index + 1 }}. {{ parseQuestion(question.fields['题目']).title }}
              </div>
              <div class="options">
                <label v-for="option in parseQuestion(question.fields['题目']).options"
                       :key="option.label"
                       class="option-item">
                  <input type="radio" 
                         :name="'single-' + index"
                         :value="option.label"
                         v-model="answers['single-' + index]"
                         @change="handleAnswerChange('single-' + index)">
                  {{ option.label }}. {{ option.text }}
                </label>
              </div>
            </div>
          </div>

          <!-- 多选题 -->
          <div v-if="randomMultiQuestions.length > 0" class="question-section">
            <h2>二、多选题（共{{ examConfig.multiCount }}题，每题{{ examConfig.scores.multi }}分）</h2>
            <div v-for="(question, index) in randomMultiQuestions" 
                 :key="question.record_id"
                 :id="'multi-' + index"
                 class="question-item">
              <div class="question-title">
                {{ index + 1 }}. {{ parseQuestion(question.fields['题目']).title }}
              </div>
              <div class="options">
                <label v-for="option in parseQuestion(question.fields['题目']).options"
                       :key="option.label"
                       class="option-item">
                  <input type="checkbox" 
                         :value="option.label"
                         v-model="answers['multi-' + index]"
                         @change="handleAnswerChange('multi-' + index)">
                  {{ option.label }}. {{ option.text }}
                </label>
              </div>
            </div>
          </div>

          <!-- 判断题 -->
          <div v-if="randomJudgeQuestions.length > 0" class="question-section">
            <h2>三、判断题（共{{ examConfig.judgeCount }}题，每题{{ examConfig.scores.judge }}分）</h2>
            <div v-for="(question, index) in randomJudgeQuestions" 
                 :key="question.record_id"
                 :id="'judge-' + index"
                 class="question-item">
              <div class="question-title">
                {{ index + 1 }}. {{ question.fields['题目'][0].text }}
              </div>
              <div class="options">
                <label class="option-item">
                  <input type="radio" 
                         :name="'judge-' + index"
                         value="正确"
                         v-model="answers['judge-' + index]"
                         @change="handleAnswerChange('judge-' + index)">
                  正确
                </label>
                <label class="option-item">
                  <input type="radio" 
                         :name="'judge-' + index"
                         value="错误"
                         v-model="answers['judge-' + index]"
                         @change="handleAnswerChange('judge-' + index)">
                  错误
                </label>
              </div>
            </div>
          </div>

          <!-- 填空题 -->
          <div v-if="randomFillQuestions.length > 0" class="question-section">
            <h2>四、填空题（共{{ examConfig.fillCount }}题，每题{{ examConfig.scores.fill }}分）</h2>
            <div v-for="(question, index) in randomFillQuestions" 
                 :key="question.record_id"
                 :id="'fill-' + index"
                 class="question-item">
              <div class="question-title">
                {{ index + 1 }}. {{ question.fields['题目'][0].text }}
              </div>
              <div class="answer-area">
                <input type="text" 
                       v-model="answers['fill-' + index]"
                       @change="handleAnswerChange('fill-' + index)"
                       placeholder="请输入答案">
              </div>
            </div>
          </div>

          <!-- 简答题 -->
          <div v-if="randomEssayQuestions.length > 0" class="question-section">
            <h2>五、简答题（共{{ examConfig.essayCount }}题，每题{{ examConfig.scores.essay }}分）</h2>
            <div v-for="(question, index) in randomEssayQuestions" 
                 :key="question.record_id"
                 :id="'essay-' + index"
                 class="question-item">
              <div class="question-title">
                {{ index + 1 }}. {{ question.fields['题目'][0].text }}
              </div>
              <div class="answer-area">
                <textarea 
                  v-model="answers['essay-' + index]"
                  @change="handleAnswerChange('essay-' + index)"
                  placeholder="请输入答案"
                  rows="4"
                ></textarea>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 移出答题区域的提交按钮 -->
      <div class="submit-wrapper">
        <button class="submit-button" @click="showConfirmDialog">
          提交考卷
        </button>
      </div>
    </div>

    <!-- 右侧信息面板 -->
    <div class="info-panel right-panel">
      <h3>考试信息</h3>
      <div class="info-content">
        <div class="info-item">
          <span class="info-label">考试人：</span>
          <span class="info-value">{{ examConfig.userName }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">题库分类：</span>
          <span class="info-value">{{ examConfig.category }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">已用时间：</span>
          <span class="info-value">{{ formatDuration }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">开始时间：</span>
          <span class="info-value">{{ startTime }}</span>
        </div>
      </div>
    </div>

    <!-- 自定义确认对话框 -->
    <div v-if="showDialog" class="dialog-mask" @click="closeDialog">
      <div class="dialog-content" @click.stop>
        <h3>确认提交</h3>
        <div class="dialog-body">
          <template v-if="unansweredQuestions.length">
            <div class="warning-message">
              <i class="warning-icon">⚠️</i>
              <div class="warning-text">
                <p>您还有题目未完成：</p>
                <ul>
                  <li v-for="(q, index) in unansweredQuestions" :key="index">
                    {{ q.type }}还有{{ q.count - q.answered }}题未完成
                  </li>
                </ul>
              </div>
            </div>
          </template>
          <p class="confirm-text">确定要提交考卷吗？</p>
        </div>
        <div class="dialog-footer">
          <button class="cancel-btn" @click="closeDialog">取消</button>
          <button class="confirm-btn" @click="handleSubmitExam">确认提交</button>
        </div>
      </div>
    </div>

    <!-- 添加加载状态遮罩 -->
    <div v-if="submitting" class="loading-mask">
      <div class="loading-content">
        <div class="loading-spinner"></div>
        <div class="loading-text">正在提交考卷...</div>
      </div>
    </div>

    <!-- 添加提交成功对话框 -->
    <div v-if="showSuccessDialog" class="dialog-mask">
      <div class="dialog-content">
        <h3>提交成功</h3>
        <div class="dialog-body">
          <div class="success-message">
            <i class="success-icon">✅</i>
            <p>考卷已成功提交！</p>
          </div>
          <div class="note-message">
            <p>注意：AI评分填空/简答题大约需要2分钟</p>
          </div>
        </div>
        <div class="dialog-footer">
          <button class="confirm-btn" @click="handleGoHome">返回首页</button>
          <button class="confirm-btn" @click="handleOpenTable">打开多维表</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useExamStore } from '../stores/exam'

// 路由实例，用于获取路由参数
const route = useRoute()
const router = useRouter()
// 考试状态管理实例
const examStore = useExamStore()
// 试卷详情数据
const examDetail = ref(null)
// 页面加载状态
const loading = ref(true)

// 试卷配置信息
const examData = ref(JSON.parse(route.query.examData))

const examConfig = computed(() => ({
  singleCount: examData.value.exam.counts.single,
  multiCount: examData.value.exam.counts.multi,
  judgeCount: examData.value.exam.counts.judge,
  fillCount: examData.value.exam.counts.fill,
  essayCount: examData.value.exam.counts.essay,
  examId: examData.value.exam.id,
  examName: examData.value.exam.name || '未命名试卷',
  userName: examData.value.user.name || '未知考生',
  category: examData.value.exam.category || '未知分类',
  scores: {
    single: examData.value.exam.scores.single,
    multi: examData.value.exam.scores.multi,
    judge: examData.value.exam.scores.judge,
    fill: examData.value.exam.scores.fill,
    essay: examData.value.exam.scores.essay
  }
}))

// 计时相关
const startTime = ref(new Date().toLocaleString())
const duration = ref(0)
const timer = ref(null)

// 格式化时间
const formatDuration = computed(() => {
  const hours = Math.floor(duration.value / 3600)
  const minutes = Math.floor((duration.value % 3600) / 60)
  const seconds = duration.value % 60
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
})

// 答题进度
const totalQuestions = computed(() => {
  return examConfig.value.singleCount + 
         examConfig.value.multiCount + 
         examConfig.value.judgeCount + 
         examConfig.value.fillCount + 
         examConfig.value.essayCount
})

const answeredCount = computed(() => answeredQuestions.value.size)

// 按题型分类题目
const questionsByType = computed(() => {
  if (!examStore.examQuestions.length) return {}
  const types = {
    single: examStore.examQuestions.filter(q => q.fields['题型'] === '单选'),
    multi: examStore.examQuestions.filter(q => q.fields['题型'] === '多选'),
    judge: examStore.examQuestions.filter(q => q.fields['题型'] === '判断'),
    fill: examStore.examQuestions.filter(q => q.fields['题型'] === '填空'),
    essay: examStore.examQuestions.filter(q => q.fields['题型'] === '简答')
  }
  
  // 检查题目数量是否足够
  const checkCount = (type, required) => {
    if (types[type].length < required) {
      console.warn(`${type}题题库数量不足：需要${required}题，实际只有${types[type].length}题`)
    }
  }
  
  checkCount('single', examConfig.value.singleCount)
  checkCount('multi', examConfig.value.multiCount)
  checkCount('judge', examConfig.value.judgeCount)
  checkCount('fill', examConfig.value.fillCount)
  checkCount('essay', examConfig.value.essayCount)
  
  return types
})

// 随机抽取指定数量的题目
const getRandomQuestions = (questions, count) => {
  if (!questions || !questions.length) return []
  // 如果题目数量不够，返回所有题目
  if (questions.length <= count) return questions
  
  // Fisher-Yates 洗牌算法
  const result = []
  const used = new Set()
  
  while (result.length < count) {
    const index = Math.floor(Math.random() * questions.length)
    if (!used.has(index)) {
      used.add(index)
      result.push(questions[index])
    }
  }
  
  return result
}

// 各类型随机题目
const randomSingleQuestions = computed(() => 
  getRandomQuestions(questionsByType.value.single, examConfig.value.singleCount)
)
const randomMultiQuestions = computed(() => 
  getRandomQuestions(questionsByType.value.multi, examConfig.value.multiCount)
)
const randomJudgeQuestions = computed(() => 
  getRandomQuestions(questionsByType.value.judge, examConfig.value.judgeCount)
)
const randomFillQuestions = computed(() => 
  getRandomQuestions(questionsByType.value.fill, examConfig.value.fillCount)
)
const randomEssayQuestions = computed(() => 
  getRandomQuestions(questionsByType.value.essay, examConfig.value.essayCount)
)

// 答案存储
const answers = ref({})
// 已答题目记录
const answeredQuestions = ref(new Set())

// 添加题目解析缓存
const questionParseCache = new Map()

// 解析题目和选项
const parseQuestion = (questionText) => {
  // 生成缓存key
  const cacheKey = questionText

  // 如果已经解析过，直接返回缓存结果
  if (questionParseCache.has(cacheKey)) {
    return questionParseCache.get(cacheKey)
  }

  // 如果 questionText 是数组，先合并成字符串
  let fullText = ''
  if (Array.isArray(questionText)) {
    fullText = questionText.map(item => item.text).join('')
  } else {
    fullText = questionText
  }

  // 按换行符分割
  const lines = fullText.split('\n').map(line => line.trim()).filter(line => line)
  
  // 查找第一个选项的位置
  const optionStartIndex = lines.findIndex(line => /^[A-H][^a-zA-Z\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff]/.test(line))
  
  // 如果没有找到选项，返回整个文本作为题目
  if (optionStartIndex === -1) {
    return {
      title: fullText,
      options: []
    }
  }

  // 提取题目（选项之前的所有行）
  const title = lines.slice(0, optionStartIndex).join('\n')
  
  // 提取选项
  const options = []
  const optionPattern = /^([A-H])[^a-zA-Z\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff](.+)$/
  
  for (let i = optionStartIndex; i < lines.length; i++) {
    const line = lines[i]
    const match = line.match(optionPattern)
    
    if (match) {
      const [_, label, text] = match
      options.push({
        label,
        text: text.trim()
      })
    }
  }
  
  // 验证选项
  if (options.length === 0) {
    console.warn('题目选项解析失败:', {
      title,
      fullText,
      lines
    })
  } else {
    // 验证选项标签是否连续
    const labels = options.map(opt => opt.label)
    const expectedLabels = Array.from({ length: options.length }, (_, i) => 
      String.fromCharCode(65 + i)
    )
    
    if (!labels.every((label, i) => label === expectedLabels[i])) {
      console.warn('题目选项标签不连续:', {
        title,
        options,
        expectedLabels
      })
    }
  }

  // 缓存并返回结果
  const result = { title, options }
  questionParseCache.set(cacheKey, result)
  
  return result
}

// 处理答案变化
const handleAnswerChange = (questionId) => {
  if (answers.value[questionId]) {
    answeredQuestions.value.add(questionId)
  } else {
    answeredQuestions.value.delete(questionId)
  }
}

// 滚动到指定题目
const scrollToQuestion = (questionId) => {
  const element = document.getElementById(questionId)
  if (element) {
    element.scrollIntoView({ behavior: 'smooth', block: 'start' })
  }
}

// 获取试卷详情的方法
const fetchExamDetail = async () => {
  try {
    const examId = examData.value.exam.id
    const category = examData.value.exam.category
    const result = await examStore.fetchExamDetail(examId, category)
    if (result) {
      examDetail.value = result
    }
  } catch (error) {
    console.error('获取试卷详情失败：', error)
  } finally {
    loading.value = false
  }
}

// 初始化多选题答案为空数组
const initAnswers = () => {
  examConfig.value.multiCount && Array(examConfig.value.multiCount).fill(null).forEach((_, index) => {
    answers.value[`multi-${index}`] = []
  })
}

// 防作弊相关变量
const windowSwitchCount = ref(0)
const showDialog = ref(false)
const unansweredQuestions = ref([])

// 添加成功对话框控制变量
const showSuccessDialog = ref(false)

// 监听页面可见性变化
onMounted(() => {
  document.addEventListener('visibilitychange', handleVisibilityChange)
  fetchExamDetail()
  initAnswers()
  // 开始计时
  timer.value = setInterval(() => {
    duration.value++
  }, 1000)
})

onUnmounted(() => {
  document.removeEventListener('visibilitychange', handleVisibilityChange)
  if (timer.value) {
    clearInterval(timer.value)
  }
  // 清理题目解析缓存
  questionParseCache.clear()
})

// 处理页面切换
const handleVisibilityChange = () => {
  if (document.hidden) {
    windowSwitchCount.value++
    console.log('切换窗口次数:', windowSwitchCount.value)
  }
}

// 显示确认对话框
const showConfirmDialog = () => {
  unansweredQuestions.value = getUnansweredQuestions()
  showDialog.value = true
}

// 关闭对话框
const closeDialog = () => {
  showDialog.value = false
}

// 格式化答案数据
const formatAnswersForSubmit = () => {
  const allQuestions = [
    ...randomSingleQuestions.value.map((q, i) => ({ type: 'single', index: i, question: q })),
    ...randomMultiQuestions.value.map((q, i) => ({ type: 'multi', index: i, question: q })),
    ...randomJudgeQuestions.value.map((q, i) => ({ type: 'judge', index: i, question: q })),
    ...randomFillQuestions.value.map((q, i) => ({ type: 'fill', index: i, question: q })),
    ...randomEssayQuestions.value.map((q, i) => ({ type: 'essay', index: i, question: q }))
  ]

  return allQuestions.map(({ type, index, question }) => {
    let answer = answers.value[`${type}-${index}`]
    
    // 处理多选题答案
    if (type === 'multi' && Array.isArray(answer)) {
      // 对选项进行排序并连接
      answer = answer.sort().join('')
    }
    
    return {
      questionId: question.record_id,
      answer: answer?.toString() || '',
      userId: examData.value.user.id,
      examId: examData.value.exam.id,
      startTime: new Date(startTime.value).getTime(),
      duration: formatDuration.value
    }
  })
}

// 添加提交状态
const submitting = ref(false)

// 检查未完成的题目
const getUnansweredQuestions = () => {
  const allQuestions = [
    { type: '单选题', count: examConfig.value.singleCount, answered: 0 },
    { type: '多选题', count: examConfig.value.multiCount, answered: 0 },
    { type: '判断题', count: examConfig.value.judgeCount, answered: 0 },
    { type: '填空题', count: examConfig.value.fillCount, answered: 0 },
    { type: '简答题', count: examConfig.value.essayCount, answered: 0 }
  ]

  // 统计已答题数
  answeredQuestions.value.forEach(id => {
    const [type] = id.split('-')
    const questionType = {
      'single': 0,
      'multi': 1,
      'judge': 2,
      'fill': 3,
      'essay': 4
    }[type]
    if (questionType !== undefined) {
      allQuestions[questionType].answered++
    }
  })

  // 返回未完成的题型
  return allQuestions.filter(q => q.answered < q.count)
}

// 修改提交处理函数
const handleSubmitExam = async () => {
  try {
    submitting.value = true
    showDialog.value = false
    
    // 1. 提交答案详情
    const formattedAnswers = formatAnswersForSubmit()
    const answersResult = await examStore.submitExamAnswers(formattedAnswers)
    
    if (!answersResult) {
      throw new Error('提交答案失败')
    }
    
    // 2. 提交考试结果
    const resultData = {
      userId: examData.value.user.id,
      examId: examData.value.exam.id,
      startTime: new Date(startTime.value).getTime(),
      duration: formatDuration.value
    }
    
    const examResult = await examStore.submitExamResult(resultData)
    
    if (!examResult) {
      throw new Error('提交考试结果失败')
    }
    
    // 显示成功对话框
    showSuccessDialog.value = true
  } catch (error) {
    console.error('提交考卷时发生错误:', error)
    alert('提交考卷时发生错误，请重试！')
  } finally {
    submitting.value = false
  }
}

// 处理返回首页
const handleGoHome = () => {
  router.push('/')
}

// 处理打开多维表
const handleOpenTable = () => {
  window.location.href = 'https://vcn2z9ewxa06.feishu.cn/wiki/DRcFwUWkDiCcXbkFCLkcFPNYnNb?table=tblohIphoUumSUU6&view=vewPUyhfiT'
}
</script>

<style scoped>
.exam {
  min-height: 100vh;
  background: url('/bg-pattern.png') center/cover fixed;
  padding: 40px 120px; /* 增加两侧内边距 */
  display: flex;
  justify-content: center;
  gap: 20px;
  position: relative;
}

.main-content {
  flex: 1;
  max-width: 900px; /* 增加最大宽度 */
  margin: 0 300px; /* 为两侧面板预留空间 */
  display: flex;
  flex-direction: column;
}

.exam-content {
  background: rgba(255, 255, 255, 0.85);
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(8px);
  margin-bottom: 40px; /* 增加底部间距 */
}

.exam-title {
  text-align: center;
  margin-bottom: 30px;
  font-size: 28px;
  font-weight: 700;
  background: linear-gradient(135deg, #3498db, #2ecc71);
  background-clip: text;
  -webkit-background-clip: text;
  color: transparent;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
}

.info-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
}

.info-label {
  color: #666;
  width: 80px;
  font-size: 14px;
}

.info-value {
  color: #2c3e50;
  font-weight: 500;
  font-size: 14px;
}

.question-nav {
  position: fixed;
  left: 120px; /* 与主内容区域对齐 */
  top: 40px;
  width: 260px;
  background: rgba(255, 255, 255, 0.85);
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  max-height: calc(100vh - 100px);
  overflow-y: auto;
  backdrop-filter: blur(8px);
}

.nav-sections {
  max-height: calc(100vh - 100px);
  overflow-y: auto;
}

.nav-section {
  margin-bottom: 20px;
}

.nav-title {
  font-weight: 600;
  margin-bottom: 10px;
  color: #2c3e50;
}

.nav-items {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.nav-item {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.nav-item:hover {
  background: rgba(240, 240, 240, 0.85);
}

.nav-item.answered {
  background: rgba(76, 175, 80, 0.85);
  color: white;
  border-color: rgba(76, 175, 80, 0.85);
}

.question-section {
  margin-bottom: 40px;
}

.question-section h2 {
  color: #2c3e50;
  margin-bottom: 25px;
  padding-bottom: 10px;
  border-bottom: 2px solid #eee;
}

.question-item {
  margin-bottom: 30px;
  padding: 20px;
  background: rgba(248, 249, 250, 0.85);
  border-radius: 8px;
  transition: all 0.3s ease;
}

.question-item:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.question-title {
  font-size: 16px;
  color: #2c3e50;
  margin-bottom: 15px;
  line-height: 1.6;
}

.options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.option-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.option-item:hover {
  background-color: rgba(240, 240, 240, 0.85);
}

.answer-area {
  margin-top: 15px;
}

.answer-area input[type="text"],
.answer-area textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

.answer-area input[type="text"]:focus,
.answer-area textarea:focus {
  outline: none;
  border-color: #3498db;
  box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
}

.answer-area textarea {
  resize: vertical;
  min-height: 100px;
}

/* 提交按钮包装器 */
.submit-wrapper {
  position: fixed;
  right: 120px; /* 与右侧面板对齐 */
  bottom: 100px; /* 预留空间给返回顶部按钮 */
  z-index: 1000;
}

.submit-button {
  background: linear-gradient(135deg, #3498db, #2980b9);
  color: white;
  padding: 16px 40px;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  font-size: 18px;
  font-weight: 600;
  letter-spacing: 1px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(52, 152, 219, 0.2);
}

.submit-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(52, 152, 219, 0.3);
}

/* 右侧信息面板样式调整 */
.right-panel {
  position: fixed;
  right: 120px; /* 与主内容区域对齐 */
  top: 40px;
  width: 260px;
  background: rgba(255, 255, 255, 0.85);
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  max-height: calc(100vh - 80px);
  overflow-y: auto;
  backdrop-filter: blur(8px);
}

/* 加载遮罩样式 */
.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-content {
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 15px;
}

.loading-text {
  color: #2c3e50;
  font-size: 16px;
  font-weight: 500;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 自定义对话框样式 */
.dialog-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.dialog-content {
  background: white;
  border-radius: 12px;
  padding: 24px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.dialog-content h3 {
  margin: 0 0 20px;
  color: #2c3e50;
  font-size: 20px;
}

.warning-message {
  display: flex;
  gap: 12px;
  background: #fff3e0;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.warning-icon {
  font-size: 24px;
}

.warning-text {
  color: #e65100;
}

.warning-text ul {
  margin: 8px 0 0;
  padding-left: 20px;
}

.confirm-text {
  text-align: center;
  color: #2c3e50;
  font-size: 16px;
  margin: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.dialog-footer button {
  padding: 10px 24px;
  border-radius: 6px;
  border: none;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s ease;
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
}

.cancel-btn:hover {
  background: #e0e0e0;
}

.confirm-btn {
  background: #3498db;
  color: white;
}

.confirm-btn:hover {
  background: #2980b9;
}

/* 响应式布局调整 */
@media (max-width: 1600px) {
  .exam {
    padding: 40px 80px;
  }
  
  .left-panel {
    left: 80px;
  }
  
  .right-panel {
    right: 80px;
  }
  
  .submit-wrapper {
    right: 80px;
  }
}

/* 成功对话框样式 */
.success-message {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.success-icon {
  font-size: 24px;
}

.success-message p {
  color: #2c3e50;
  font-size: 18px;
  margin: 0;
}

.note-message {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.note-message p {
  color: #666;
  margin: 0;
  font-size: 14px;
}

/* 修改按钮样式，确保两个按钮样式一致 */
.dialog-footer .confirm-btn {
  flex: 1;
  max-width: 200px;
  background: #3498db;
  color: white;
  padding: 12px 24px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s ease;
}

.dialog-footer .confirm-btn:hover {
  background: #2980b9;
}
</style> 